package com.ipan.okhttp.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.ipan.kits.io.IOUtil;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * Request body封装
 * 
 * 注意：构造时候的输入流，由外部关闭；
 *
 * @author iPan
 * @version 2019-12-25
 */
public class InputStreamRequestBody extends RequestBody {

    private final byte[] content;
    private final int byteCount;
    private final MediaType mediaType;

    public InputStreamRequestBody(InputStream content, MediaType mediaType) throws IOException { // content由调用者关闭
        this.mediaType = mediaType;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtil.copy(content, baos);
        this.content = baos.toByteArray();
        this.byteCount = this.content.length;
    }

    /**
     * Returns the number of bytes that will be written to {@code out} in a call to {@link #writeTo},
     * or -1 if that count is unknown.
     */
    @Override
    public long contentLength() throws IOException {
        return this.byteCount;
    }

    /**
     * Returns the Content-Type header for this body.
     */
    @Override
    public MediaType contentType() {
        return this.mediaType;
    }

    /**
     * Writes the content of this request to {@code out}.
     */
    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        sink.write(this.content, 0, this.byteCount);
    }
}
